package xyz.jcat.common.auth;

import lombok.extern.slf4j.Slf4j;
import xyz.jcat.common.util.BusinessUtils;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.common.web.RespException;

/**
 * 用户上下文
 */
@Slf4j
public class UserContextHolder {

    private ThreadLocal<Long> threadLocal;

    private UserContextHolder() {
        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * 创建实例
     *
     * @return
     */
    public static UserContextHolder getInstance() {
        return SingletonHolder.sInstance;
    }

    /**
     * 静态内部类单例模式
     * 单例初使化
     */
    private static class SingletonHolder {
        private static final UserContextHolder sInstance = new UserContextHolder();
    }

    /**
     * 用户上下文中放入信息
     *
     * @param userId
     */
    public void setUserId(Long userId) {
        threadLocal.set(userId);
    }

    /**
     * 获取上下文中的信息
     *
     * @return
     */
    public Long getUserId() {
        Long userId = threadLocal.get();
        if(BusinessUtils.isRealId(userId))
            return userId;
        log.error("userId is not exist");
        throw new RespException(RespCodeMsg.UNAUTHORIZED);
    }

    /**
     * 清空上下文
     */
    public void clear() {
        threadLocal.remove();
    }

}
